package com.dinzeer.legendreliclib.effect;

import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

public class TheMoonLove extends MobEffect {

    public TheMoonLove(MobEffectCategory category, int color) {
        super(category, color);
    }

    // 每5刻（0.25秒）触发一次
    @Override
    public boolean isDurationEffectTick(int duration, int amplifier) {
        return duration % 5 == 0;
    }

    @Override
    public void applyEffectTick(LivingEntity entity, int amplifier) {
        if (!entity.level().isClientSide) {
            // 恢复手中物品的耐久（主手和副手）
            restoreHandItemDurability(entity);
        }
    }

    private void restoreHandItemDurability(LivingEntity entity) {
        // 修复主手物品
        restoreItemDurability(entity.getMainHandItem());

        // 修复副手物品
        restoreItemDurability(entity.getOffhandItem());
    }

    private void restoreItemDurability(ItemStack stack) {
        if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > 0) {
            // 每次恢复1点耐久
            stack.setDamageValue(stack.getDamageValue() - 1);
        }
    }

    // 事件处理器
    @Mod.EventBusSubscriber
    public static class EventHandler {

        @SubscribeEvent
        public static void onLivingHurt(LivingHurtEvent event) {
            LivingEntity entity = event.getEntity();

            // 检查是否拥有月光祝福效果
            if (entity.hasEffect(LReffect.TheMoonLove.get())) { // 替换为你的效果注册
                Level world = entity.level();

                // 检查维度条件：主世界且夜晚，或其他维度（非下界/末地）
                if (isDimensionValidForEffect(world)) {
                    // 应用50%伤害减免
                    event.setAmount(event.getAmount() * 0.5F);
                }
            }
        }

        private static boolean isDimensionValidForEffect(Level world) {
            // 检查是否为主世界且夜晚
            if (world.dimension() == Level.OVERWORLD) {
                long dayTime = world.getDayTime() % 24000;
                return dayTime >= 13000 && dayTime <= 23000; // 夜晚时间段
            }

            // 检查是否为其他维度（非下界和末地）
            return world.dimension() != Level.NETHER && world.dimension() != Level.END;
        }
    }
}